const express = require('express');
const dotenv = require('dotenv');
const axios = require('axios');
const cors = require('cors');
const { Readable } = require('stream');

// 加载环境变量
dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;
const COZE_TOKEN = process.env.COZE_TOKEN || 'pat_dfbP9elnBNMDg2krNNrQUWArxfUirY76pCGlteG4shc9f2fxZ5xNKZqz9qZGiJpW';
const COZE_TOKENxiangshui = process.env.COZE_TOKENxiangshui || 'cztei_hYcbYnxM3Kin5SOjkgzOUW23l2v0aT7IgfYQ040T2feEFjRruY9RsVISa3AdCIspr';
// 中间件
app.use(express.json());
app.use(cors());

// 检查是否有COZE_TOKEN
if (!COZE_TOKEN) {
  console.error('COZE_TOKEN environment variable not set');
  process.exit(1);
}
app.get('/', async (req, res) => {
  res.send('Hello World');
});

// 获取特调鸡尾酒推荐API
app.post('/api/cocktail', async (req, res) => {
  try {
    const { mood, taste, alcohol, scene } = req.body;
    
    // 验证必要参数
    if (!mood || !taste || !alcohol || !scene) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数: mood, taste, alcohol, scene 都是必需的'
      });
    }
    
    console.log('生成鸡尾酒推荐，参数:', req.body);
    
    try {
      // 调用 Coze 工作流生成鸡尾酒推荐
      const response = await axios.post(
        'https://api.coze.cn/v1/workflow/run',
        {
          parameters: { 
            mood: mood,
            taste: taste,
            alcohol: alcohol,
            scene: scene
          },
          workflow_id: "7519427325491560482",
          app_id: "wx80ce20f02bd49b52"
        },
        {
          headers: {
            'Authorization': `Bearer ${COZE_TOKEN}`,
            'Content-Type': 'application/json'
          },
          timeout: 60000 // 60秒超时
        }
      );
      
      // 处理返回数据
      if (response.data && response.data.data) {
        try {
          console.log('Coze API响应:', response.data);
          const cocktailData = JSON.parse(response.data.data);
          
          // 返回结果
          res.json({
            success: true,
            cocktailName: cocktailData.cocktailName,
            cost: cocktailData.cost,
            imageUrl: cocktailData.data,
            formula: cocktailData.formula,
            guideline: cocktailData.guideline,
            spiritStory: cocktailData.spiritStory
          });
          return;
        } catch (parseError) {
          console.error('解析鸡尾酒数据失败:', parseError, response.data);
          throw new Error('解析鸡尾酒数据失败');
        }
      } else if (response.data && response.data.code === 4028) {
        console.log('Coze API额度不足，使用模拟数据');
        throw new Error('API额度不足');
      } else {
        console.error('API响应缺少data字段:', response.data);
        throw new Error('API响应格式错误');
      }
    } catch (apiError) {
      console.error('API调用失败，使用模拟数据:', apiError.message);
      // 使用模拟数据
      const mockData = {
        cocktailName: "林涧幽梦",
        cost: "成本约(28 元)",
        imageUrl: "https://s.coze.cn/t/yGF2iU_xaLM/",
        formula: {
          baseSpirits: "普利茅斯金酒(40ml) + 圣日耳曼接骨木花利口酒(15ml)",
          flavorElements: "柠檬汁(15ml) + 薄荷糖浆(10ml) + 薄荷叶少许 + 森林苔藓提取物(5ml)",
          garnish: "松枝串 + 水晶雨滴装饰 + 白桦树皮碎片",
          tasteProfile: "仿若漫步在雨后的森林小径，清新的柠檬与薄荷气息相伴，森林苔藓的底蕴在舌尖悄然蔓延"
        },
        guideline: {
          drinkingMethod: "选用高脚杯，轻轻搅拌后慢饮，每口间隔 1.5 分钟，品味风味层次变化",
          healthReminder: "约为 2.1 标准杯 | 糖尿病患者可使用甜菊糖苷替代糖浆 | 建议空腹或半空腹时饮用",
          idealSetting: "黄昏时分的静谧角落 | 搭配米色麻质杯垫 | 可播放森林鸟鸣音频"
        },
        spiritStory: "金酒承载着英伦的酿造传统，圣日耳曼接骨木花利口酒则带来自然的芬芳。两者结合，如同一幅雨后森林的画卷在杯中徐徐展开，清新之感沁人心脾。"
      };
      
      res.json({
        success: true,
        cocktailName: mockData.cocktailName,
        cost: mockData.cost,
        imageUrl: mockData.imageUrl,
        formula: mockData.formula,
        guideline: mockData.guideline,
        spiritStory: mockData.spiritStory
      });
      return;
    }
  } catch (error) {
    console.error('生成鸡尾酒推荐失败:', error);
    
    // 详细记录错误信息
    let errorMessage = error.message;
    
    if (error.isAxiosError) {
      console.error('Axios错误详情:', {
        timeout: error.config?.timeout,
        hasResponse: !!error.response,
        status: error.response?.status,
        responseData: error.response?.data,
        hasRequest: !!error.request,
        code: error.code
      });
      
      errorMessage = `API请求失败: ${error.message}`;
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时。推荐生成可能需要几分钟时间。';
      }
    }
    
    res.status(500).json({
      success: false,
      message: '生成鸡尾酒推荐失败',
      error: errorMessage
    });
  }
});

// 获取香水推荐API
app.post('/api/perfume', async (req, res) => {
  try {
    const { mood, weather, scene, note } = req.body;
    if (!mood || !weather || !scene || !note) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数: mood, weather, scene, note 都是必需的'
      });
    }
    console.log('生成香水推荐，参数:', req.body);
    try {
      const response = await axios({
        method: 'post',
        url: 'https://api.coze.cn/v1/workflow/stream_run',
        data: {
          workflow_id: "7519728252484370469",
          parameters: { mood, note, scene, weather }
        },
        headers: {
          'Authorization': `Bearer ${COZE_TOKENxiangshui}`,
          'Content-Type': 'application/json'
        },
        responseType: 'stream'
      });
      let result = '';
      response.data.on('data', chunk => {
        const lines = chunk.toString().split('\n');
        lines.forEach(line => {
          if (line.startsWith('data: ')) {
            const jsonStr = line.replace('data: ', '').trim();
            if (jsonStr.includes('content')) {
              try {
                const obj = JSON.parse(jsonStr);
                if (obj.content) result = obj.content;
              } catch (e) {}
            }
          }
        });
      });
      response.data.on('end', () => {
        let perfumeData = {};
        try {
          perfumeData = typeof result === 'string' ? JSON.parse(result) : result;
        } catch (e) {}
        let guideline = perfumeData.guideline;
        let ingredients = perfumeData.ingredients;
        if (typeof guideline === 'string') {
          try { guideline = JSON.parse(guideline); } catch (e) { guideline = {}; }
        }
        // 完整 ingredients 处理逻辑
        if (typeof ingredients === 'string') {
          try { ingredients = JSON.parse(ingredients); } catch (e) { ingredients = {}; }
        }
        if (!ingredients || typeof ingredients !== 'object' || Array.isArray(ingredients)) {
          ingredients = { '暂无配料信息': '' };
        }
        console.log('perfumeData:', perfumeData);
        console.log('ingredients:', ingredients);
        const pureIngredients = JSON.parse(JSON.stringify(perfumeData.ingredients || {}));
        const ingredientsArr = objToArr(pureIngredients);
        res.json({
          success: true,
          perfumeName: perfumeData.perfumeName,
          ingredients: ingredientsArr,
          guideline: guideline,
          story: perfumeData.story,
          outfitImage: perfumeData.output
        });
        if (perfumeData.perfumeName && perfumeData.outfitImage) {
          wx.request({
            url: 'http://localhost:3000/api/history',
            method: 'POST',
            data: {
              name: perfumeData.perfumeName,
              image: perfumeData.outfitImage,
              userId: '', // 如有用户ID可填写
              type: 'auto',
              category: 'perfume'
            },
            success(res) {
              console.log('香水历史推荐已保存', res.data);
            }
          });
        }
      });
      response.data.on('error', (err) => {
        console.error('SSE流处理出错:', err);
        res.status(500).json({ success: false, message: 'SSE流处理出错', error: err.message });
      });
    } catch (apiError) {
      console.error('API调用失败，使用模拟数据:', apiError.message);
      const mockData = {
        perfumeName: "晨曦花园",
        ingredients: {
          "橙花精油": "30%",
          "佛手柑精油": "20%",
          "雪松木": "15%",
          "麝香": "10%",
          "白茶": "25%"
        },
        guideline: {
          usage: "适合日常通勤、约会或独处时使用。喷洒于脉搏处，香气更持久。",
          tips: "避免阳光直射，存放于阴凉处。"
        },
        story: "在晨曦微露的花园中，少女身着白裙，沐浴着橙花与白茶的清香，开启新的一天。",
        outfitImage: "https://images.unsplash.com/photo-1517841905240-472988babdf9?auto=format&fit=crop&w=800&q=80"
      };
      res.json({ success: true, ...mockData });
      return;
    }
  } catch (error) {
    console.error('生成香水推荐失败:', error);
    res.status(500).json({ success: false, message: '生成香水推荐失败', error: error.message });
  }
});

// ====== 历史推荐内存存储 ======
let perfumeHistoryList = [];

// 新增历史推荐（POST）
app.post('/api/history', (req, res) => {
  const { name, image, userId, type, category } = req.body;
  if (!name || !image) {
    return res.status(400).json({ error: 'name and image required' });
  }
  const item = {
    id: Date.now() + Math.random().toString(36).substr(2, 5),
    name,
    image,
    userId: userId || null,
    type: type || 'auto',
    category: category || 'perfume',
    time: Date.now()
  };
  perfumeHistoryList.unshift(item);
  res.json({ success: true, item });
});

// 获取历史推荐（GET）
app.get('/api/history', (req, res) => {
  const { userId, category } = req.query;
  let result = perfumeHistoryList;
  if (userId) {
    result = result.filter(i => i.userId === userId);
  }
  if (category) {
    result = result.filter(i => i.category === category);
  }
  res.json({ success: true, list: result });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

function objToArr(obj) {
  if (!obj || typeof obj !== 'object') return [];
  return Object.keys(obj).map(key => obj[key]);
}